package cn.iocoder.yudao.module.mp.service.open;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.mp.controller.admin.open.vo.MpOpenAccessTokenResp;
import cn.iocoder.yudao.module.mp.controller.admin.open.vo.MpOpenUserBasicResp;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.stereotype.Service;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;


/**
 * @Author cjc
 * @Date 2024/7/3 17:07
 * @Description: 用户信息
 * @Version 1.0
 */
@Service
public class MpUserBasicServiceImpl implements MpUserBasicService{

    private final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code" ;

    private final String USER_BASIC_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN" ;

    private final String APP_ID = "wx8a9d5714ee3d4a00";

    private final String APP_SECRET = "8b2de692defc895605109ef5c5b21388";


    @Override
    public MpOpenUserBasicResp getUserBasic(String code){
        MpOpenAccessTokenResp accessToken = getAccessToken(code);
        if (accessToken == null){
            throw exception(500,"获取access_token失败");
        }
        String userBasicUrl = String.format(USER_BASIC_URL,accessToken.getAccessToken(),accessToken.getOpenId());
        String s = null;
        MpOpenUserBasicResp userBasicResp = null;
        try{
            s =  HttpUtil.get(userBasicUrl);
            userBasicResp = JSONUtil.toBean(s,MpOpenUserBasicResp.class);
        }catch (Exception e){
            throw exception(500,"获取用户信息失败");
        }
        return userBasicResp;
    }

    private MpOpenAccessTokenResp getAccessToken(String code){
        String tokenUrl = String.format(ACCESS_TOKEN_URL,APP_ID,APP_SECRET,code);
        String s = null;
        MpOpenAccessTokenResp accessTokenResp = null;
        try{
           s =  HttpUtil.get(tokenUrl);
           accessTokenResp = JSONUtil.toBean(s,MpOpenAccessTokenResp.class);
        }catch (Exception e){
            return null;
        }
        return accessTokenResp;
    }
}
